// import { legacy_createStore as createStore } from 'redux'
import {
  configureStore, // 用于创建仓库
  createAction, // 动态生成 action
  createReducer, // 创建 reducer 处理器函数
} from '@reduxjs/toolkit'
import logger from 'redux-logger'

const add = createAction('ADD') // 获取一个 add 函数 可以返回 动作类型是 "ADD" 的 action 动作对象
const minus = createAction('MINUS', (payload) => { // 动态生成 payload
  return {
    payload: payload * 2 // 传递的参数 * 2 
  }
})
console.log(add)

// function reducer(state = { number: 0 }, action) {
//   switch (action.type) {
//     case add.type: {
//       return { number: state.number + 1 }
//     }
//     case minus.type: {
//       return { number: state.number - action.payload  }
//     }
//     default: {
//       return state
//     }
//   }
// }

// 对象的 key 如果是变量会自动调用 toString 方法
// const reducer = createReducer({number: 0}, {
//   [add]: (state, action) => {
//     return {number: state.number + 1}
//   },
//   [minus]: (state, action) => {
//     return {number: state.number - action.payload}
//   }
// })

const reducer = createReducer({ number: 0 }, builder => {
  builder
    .addCase(add, (state, action) => {
      // return { ...state, number: state.number + 1 }
      state.number++
    })
    .addCase(minus, (state, action) => {
      // return { ...state, number: state.number - action.payload }
      state.number = state.number - action.payload
    })
})

// const store = createStore(reducer)
const store = configureStore({
  reducer, // 配置 reducer 处理器函数
  middleware: defaultMiddlewares => [...defaultMiddlewares(), logger], // 合并内置中间件
  preloadedState: { number: 5 },
})

let valueEl = document.getElementById('value')

function render() {
  valueEl.innerHTML = store.getState().number
}

render()

store.subscribe(render)

document.getElementById('add').addEventListener('click', () => store.dispatch(add()))

document.getElementById('minus').addEventListener('click', () => store.dispatch(minus(2)))

// 有内置的 redux-thunk 中间件 dispatch 可以接收一个函数作为参数
document.getElementById('asyncAdd').addEventListener('click', () => store.dispatch((dispatch) => {
  setTimeout(() => {
    dispatch(add())
  }, 1000)
}))
